/**
 * 菜单对象
 * @type object
 * @since 1.0 <2015-6-19> SoChishun Added.
 * @since 2.0 <2015-6-23> SoChishun 重构为 indexedDB引擎
 */
var SuNavMenu = {
    newInstance: function () {

        var obj = {
            /**
             * 数据库实例
             */
            db: null,
            /**
             * 配置选项
             */
            config: {
                debug: false,
                store_name: 'nav_menu',
                sign: '',
                url: '',
                version: 6,
                after_reload_fn: function (menus) {
                },
                menu_click_fn: function ($a) {
                },
            },
            /**
             * 设置配置选项
             * @since 1.0 <2015-6-19> SoChishun Added.
             */
            set_config: function (options) {
                $.extend(this.config, options);
            },
            /**
             * 记录日志
             * @param string fn
             * @param string msg
             * @since 1.0 <2015-6-23> SoChishun Added.
             */
            log: function (fn, msg) {
                if (this.config.debug) {
                    console.log('SuNavMenu 2.0 [' + fn + ']: ' + msg);
                }
            },
            /**
             * 打开数据库
             * @since 1.0 <2015-6-23> SoChishun Added.
             */
            open_db: function () {
                if (!window.indexedDB)
                {
                    alert("你的浏览器不支持IndexedDB,请更换为现代浏览器!");
                    return;
                }
                var request = window.indexedDB.open(this.config.store_name, this.config.version);
                request.onerror = function (e) {
                    obj.log('open_db', e.currentTarget.error.message);
                };
                request.onsuccess = function (e) {
                    obj.db = e.target.result;
                    obj.log('open_db', 'Open Success!');
                    obj.load_menu();
                };
                request.onupgradeneeded = function (e) {
                    var db = e.target.result;
                    if (db.objectStoreNames.contains(obj.config.store_name)) {
                        obj.log('open_db.onupgradeneeded', 'delete success');
                        db.deleteObjectStore(obj.config.store_name);
                    }
                    db.createObjectStore(obj.config.store_name, {keyPath: 'sign'});
                    obj.log('open_db', 'DB version changed to ' + obj.config.version);
                };
            },
            /**
             * 初始化
             * @since 1.0 <2015-6-19> SoChishun Added.
             */
            init: function () {
                this.open_db(this.config.store_name);
            },
            /**
             * 加载菜单
             * @since 1.0 <2015-6-19> SoChishun Added.
             */
            load_menu: function () {
                // sign=sha1(rule);
                // {sign:"",menus:[{id:"",name:"",url:""}...]}
                if (!this.db.objectStoreNames.contains(this.config.store_name)) {
                    obj.ajax_load_menu();
                    return;
                }
                var req = this.db.transaction([this.config.store_name], 'readonly').objectStore(this.config.store_name).get(this.config.sign);
                req.onerror = function (e) {
                    obj.log('load_menu', e.currentTarget.error.message);
                    obj.ajax_load_menu();
                }
                req.onsuccess = function (e) {
                    var omenu = e.target.result;
                    if (!omenu) {
                        obj.ajax_load_menu();
                    } else {
                        if (obj.config.sign !== omenu.sign) {
                            // 签名不一致,重新加载菜单
                            obj.ajax_load_menu();
                        } else {
                            obj.build_menu(omenu.menus);
                        }
                    }
                };
            },
            /**
             * 远程加载菜单
             * @since 1.0 <2015-6-19> SoChishun Added.
             * @since 1.1 <2015-6-29> SoChishun 增加清空表的功能
             */
            ajax_load_menu: function () {
                $.ajax({
                    method: 'POST',
                    dataType: 'JSON',
                    url: this.config.url,
                    success: function (data) {
                        // {status:true,info:[{id:"",name:"",url:""}...]}
                        if (data.status) {
                            obj.db.transaction([obj.config.store_name], 'readwrite').objectStore(obj.config.store_name).clear().onsuccess = function () {
                                obj.db.transaction([obj.config.store_name], 'readwrite').objectStore(obj.config.store_name).put({"sign": obj.config.sign, "menus": data.info});
                                obj.build_menu(data.info); // 加载成功,重新刷新菜单
                            };

                        } else {
                            alert(data.info);
                        }
                    },
                    error: function () {
                        alert('菜单数据加载失败!')
                    },
                });
            },
            /**
             * 生成菜单,可重构
             * @param Array menus
             * @since 1.0 <2015-6-19> SoChishun Added.
             * @since 1.1 <2015-7-2> SoChishun 修正子菜单点击执行menu_click_fn()参数错误的问题
             */
            build_menu: function (menus) {
                if (!menus) {
                    alert('没有菜单数据!');
                    return;
                }
                var mm = '';
                var submm = '';
                $(menus).each(function () {
                    mm += '<a id="nav_' + this.id + '" href="javascript:void(0)">' + this.name + '</a>';
                    submm += '<div id="nav_sub_' + this.id + '" class="main-nav-sub">';
                    $(this.children).each(function () {
                        $(this.children).each(function () {
                            submm += '<div><a href="' + this.url.replace('/XCall/', '/XCall_5_0/') + '" data-id="' + this.id + '">' + this.name + '</a></div>';
                        })
                    })
                    submm += '</div>';
                })
                $('#main_nav').html(mm);
                $(submm).menu();
                $(menus).each(function () {
                    $('#nav_' + this.id).menubutton({menu: '#nav_sub_' + this.id, iconCls: this.code});
                })
                $('.main-nav-sub').delegate('a', 'click', function () {
                    obj.config.menu_click_fn($(this));
                })
                this.config.after_reload_fn(menus); // 生成菜单成功,执行后续操作,如重建导航Tab
            },
            /**
             * 跳转
             * @param int id
             * @since 1.0 <2015-6-23> SoChishun Added.
             */
            redirect: function (id) {
                var req = this.db.transaction([this.config.store_name], 'readonly').objectStore(this.config.store_name).get(this.config.sign);
                req.onerror = function (e) {
                    obj.log('load_menu', e.currentTarget.error.message);
                    obj.ajax_load_menu();
                }
                req.onsuccess = function (e) {
                    var omenu = e.target.result;
                    $(omenu.menus).each(function () {
                        $(this.children).each(function () {
                            $(this.children).each(function () {
                                if (id == this.id) {
                                    location.href = this.url.replace('/XCall/', '/XCall_5_0/');
                                    return;
                                }
                            })
                        })
                    })
                }
            },
        };
        return obj;
    }
};